package com.xk.controller;

import com.xk.pojo.User;
import com.xk.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public String login(HttpServletRequest request,
                        HttpServletResponse response, User user, Model model){

        boolean checklogin = userService.checklogin(user);
        System.out.println(checklogin+"登录信息");
        //如果登录错误
        if (checklogin!=true){
            model.addAttribute("msg","用户名或者密码错误");
            return "login";
        }

        Cookie logincookie = new Cookie("login",
                user.getUsername()+"-"+user.getPassword());
        //设置Cookie的路径
        logincookie.setPath("/");
        //设置Cookie的存活时间1小时
        logincookie.setMaxAge(3600); // 例如，存活1小时
        //添加Cookie
        response.addCookie(logincookie);

        return "teacherlist";
    }

    /**
     * 注册
     * @param user
     * @return
     */
    @RequestMapping("/register")
    public String register(User user,Model model){
        int i = userService.addUser(user);
        model.addAttribute("msg","注册成功");
        return "login";
    }
    @RequestMapping("/logout")
    public String logout(HttpServletRequest request,HttpServletResponse response){
        //删除旧Cookie并且回到登录页面
        Cookie cookie = new Cookie("login", null);
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        return "redirect:/login.jsp";
    }

    @RequestMapping("/gotologin")
    public String gotologin(HttpServletRequest request,HttpServletResponse response){

        return "login";
    }
    @RequestMapping(value = "/forward", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView forward(HttpServletRequest request) {
        String url = request.getParameter("login");
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName(url);
        return modelAndView;
    }

}
